package com.asset.salesforce.controller;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.asset.salesforce.converter.LeadConverter;
import com.asset.salesforce.domain.Account;
import com.asset.salesforce.domain.ActionType;
import com.asset.salesforce.domain.Appointment;
import com.asset.salesforce.domain.Call;
import com.asset.salesforce.domain.City;
import com.asset.salesforce.domain.Contact;
import com.asset.salesforce.domain.ConvertedAccount;
import com.asset.salesforce.domain.Country;
import com.asset.salesforce.domain.DeletedLead;
import com.asset.salesforce.domain.Employee;
import com.asset.salesforce.domain.Lead;
import com.asset.salesforce.domain.Role;
import com.asset.salesforce.domain.UpdateChatter;
import com.asset.salesforce.domain.User;
import com.asset.salesforce.enums.FOLLOWTYPE;
import com.asset.salesforce.enums.INDUSTRY;
import com.asset.salesforce.enums.LEADSOURCE;
import com.asset.salesforce.enums.LEADSTATUS;
import com.asset.salesforce.enums.PRIORITY;
import com.asset.salesforce.enums.RATING;
import com.asset.salesforce.enums.STATUS;
import com.asset.salesforce.enums.UPDATETYPE;
import com.asset.salesforce.enums.VIEWTYPE;
import com.asset.salesforce.form.AccountConvertForm;
import com.asset.salesforce.form.ExcelAssetLead;
import com.asset.salesforce.form.GenericCrud;
import com.asset.salesforce.form.LeadColumnsForm;
import com.asset.salesforce.form.LeadForm;
import com.asset.salesforce.service.AccountService;
import com.asset.salesforce.service.ActionFieldService;
import com.asset.salesforce.service.ActionTypeService;
import com.asset.salesforce.service.AppointmentService;
import com.asset.salesforce.service.CalendarService;
import com.asset.salesforce.service.CallService;
import com.asset.salesforce.service.CityService;
import com.asset.salesforce.service.ContactService;
import com.asset.salesforce.service.ConvertedAccountService;
import com.asset.salesforce.service.CountryService;
import com.asset.salesforce.service.DeletedLeadService;
import com.asset.salesforce.service.EmployeeService;
import com.asset.salesforce.service.JoinRequestService;
import com.asset.salesforce.service.LeadService;
import com.asset.salesforce.service.PostService;
import com.asset.salesforce.service.UpdateChatterService;
import com.asset.salesforce.service.UserShiroService;
import com.asset.salesforce.service.ViewService;
import com.myjeeva.poi.ExcelReader;
import com.myjeeva.poi.ExcelWorkSheetHandler;
//import com.asset.salesforce.domain.Priority;
//import com.asset.salesforce.domain.Rating;
//import com.asset.salesforce.domain.Status;
//import com.asset.salesforce.domain.UpdateType;
//import com.asset.salesforce.service.FollowTypeService;
//import com.asset.salesforce.service.IndusteryService;
//import com.asset.salesforce.service.LeadSourceService;
//import com.asset.salesforce.service.LeadStatusService;
//import com.asset.salesforce.service.Priorityservice;
//import com.asset.salesforce.service.RatingService;
//import com.asset.salesforce.service.StatusService;
//import com.asset.salesforce.service.UpdateTypeService;

@Controller
public class LeadController {
	@Autowired
	private LeadService leadService;
	@Value("${lead.leadOwner}")
    String exprnOffset;
	
	@Autowired
	private  EmployeeService employeeService;
	
//	@Autowired
//	private ExcelAssetLead excelAssetLead;
//	
//	@Autowired
//	private ExcelLead excelLead;
	
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private ConvertedAccountService convertedAccountService;
	
	@Autowired 
	private CountryService countryService;
	
	@Autowired
	private CityService cityService;
	
	@Autowired
	private ContactService contactService;
	

	@Autowired
	private ViewService viewService;

	@Autowired
	private CallService callService;
	
	@Autowired
	private AppointmentService appointmentService;
	
	@Autowired 
	private UpdateChatterService  updateChatterService;
	
	@Autowired
	private PostService postService;
	
	@Autowired
	private DeletedLeadService deletedLeadService;
	
	@Autowired
	private ActionTypeService actionTypeService;
	
	@Autowired
	private ActionFieldService actionFieldService;
	
	@Autowired
	private JoinRequestService joinRequestService;
	
	@Autowired
	private CalendarService calendarService;
	@Autowired
	private UserShiroService userShiroService;
	
	@RequestMapping(value="/convert-lead" ,method=RequestMethod.GET)
	public String getConvertLead(Model model ,HttpSession session ,HttpServletRequest request ,HttpServletResponse response,ModelMap modelMap){
		if (SecurityUtils.getSubject().hasRole("leadConvert")){		
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/s/login.html";
		}
		Employee userDetails = (Employee)session.getAttribute("userDetails");
		model.addAttribute("userDetails",userDetails);
		
		//get lead info
		Integer id = Integer.parseInt(request.getParameter("id").toString());
		Lead lead = leadService.getLeadById(id);
		model.addAttribute("lead", lead);
		LEADSTATUS[] leadStatus = LEADSTATUS.values();
		model.addAttribute("leadStatus", leadStatus);
		STATUS[] status = STATUS.values();
		model.addAttribute("status", status);
		PRIORITY[] priorities = PRIORITY.values();
		model.addAttribute("priorities", priorities );
		AccountConvertForm convertForm = new AccountConvertForm();
		convertForm.setAccountOwner(userDetails.getfName());
		if(lead.getLeadStatus() != null){
			convertForm.setConvertedStatus(lead.getLeadStatus());
		}
		modelMap.addAttribute("convertForm", convertForm);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "convert-lead";
		}
		else{
			return "accessDenied";
		}
	}
	@RequestMapping(value="/convert-lead" ,method=RequestMethod.POST)
	public String postConvertLead(Model model ,HttpSession session ,HttpServletRequest request,HttpServletResponse response,
			@Valid @ModelAttribute("convertForm") AccountConvertForm convertForm ,BindingResult result,
			@RequestParam(value="leadId",required=false)Integer leadId,ModelMap modelMap){
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if(result.hasErrors()){
			Employee userDetails = (Employee)session.getAttribute("userDetails");
			model.addAttribute("userDetails",userDetails);
			joinRequestService.getJoinRquestNo(session, model);
			calendarService.getAppointmentEventsNo(session, model);
			calendarService.getCallEventssNo(session, model);
			//get lead info
			Integer id = leadId;
			Lead lead = leadService.getLeadById(id);
			model.addAttribute("lead", lead);
			LEADSTATUS[] leadStatus = LEADSTATUS.values();
			model.addAttribute("leadStatus", leadStatus);
			STATUS[] status = STATUS.values();
			model.addAttribute("status", status);
			PRIORITY[] priorities = PRIORITY.values();
			model.addAttribute("priorities", priorities );
			convertForm.setAccountOwner(userDetails.getfName());
			if(lead.getLeadStatus() != null){
				convertForm.setConvertedStatus(lead.getLeadStatus());	
			}
			modelMap.addAttribute("convertForm", convertForm);
			return "convert-lead";
			
		}
		Employee userDetails = (Employee)session.getAttribute("userDetails");
		Lead lead = leadService.getLeadById(leadId);
		//lead.set
		LEADSTATUS[] leadStatus = LEADSTATUS.values();
		PRIORITY[] priorities = PRIORITY.values();
		STATUS[] status = STATUS.values();
		Account account = new Account();
		account.setAccountCreator(userDetails);
		account.setAccountName(convertForm.getAccountName());
		account.setCompanyName(lead.getCompanyName());
		if(lead.getAnnualRevenue() !=null){
			account.setAnnualRevenue(lead.getAnnualRevenue());
		}
		if(lead.getCity() !=null){
			account.setCity(lead.getCity());
		}
		if(lead.getCountry() !=null){
			account.setCountry(lead.getCountry());
		}
			account.setDateCreated(new Date());
		if(lead.getDescription() !=null){
			account.setDescription(lead.getDescription());
		}
		if(lead.getEmail() !=null){
			account.setEmail(lead.getEmail());
		}
		if(lead.getIndustry() !=null){
			account.setIndustry(lead.getIndustry());
		}
		if(lead.getIsFollowed() !=null){
			account.setIsFollowed(lead.getIsFollowed());
		}
		if(lead.getPhone() !=null){
			account.setPhone(lead.getPhone());
		}
		if(lead.getMobile() !=null){
			account.setMobile(lead.getMobile());
		}
		if(lead.getState() !=null){
			account.setState(lead.getState());
		}if(lead.getStreet() !=null){
			account.setStreet(lead.getStreet());
		}
		if(lead.getWebSite() !=null){
			account.setWebSite(lead.getWebSite());
		}
		if(lead.getZipCode() !=null){
			account.setZipCode(lead.getZipCode());
		}
		account.setIsDeleted(false);
		Date date= new Date();
		account.setDateCreated(date);
		account.setDateModified(date);
		accountService.addAccount(account);
		ConvertedAccount convertedAccount = new ConvertedAccount();
		convertedAccount.setAccount(account);
		convertedAccount.setAccountOwner(userDetails);
		convertedAccount.setAcoountName(convertForm.getAccountName());
		convertedAccount.setComments(convertForm.getComments());
		convertedAccount.setLead(lead);
		convertedAccount.setLeadStatus(convertForm.getConvertedStatus());
		convertedAccount.setNewDate(new Date());
		convertedAccount.setOpportunityName(convertForm.getOpportiunityName());
		convertedAccount.setPriority(convertForm.getPriority());
		convertedAccount.setStatus(convertForm.getStatus());
		convertedAccount.setSubject(convertForm.getSubject());
		convertedAccountService.addConvertedAccount(convertedAccount);
		lead.setIsConverted(true);
		lead.setDateModified(date);
		leadService.saveOrupdate(lead);
		//change parent id and tyoe for contact to account
		List<Contact> contacts = contactService.getContactByParent("lead", lead.getId());
		
		for(Contact contact : contacts){
			contact.setViewType("account");
			contact.setParentId(account.getId());
			contact.setDateModified(date);
			contactService.saveOrUpdate(contact);
		}
		//
		//save post to view on chatter page
//		FollowType followType = followTypeService.getFollowTypeById(4);
				UpdateChatter updateChatter = new UpdateChatter();
				updateChatter.setAction_emp(userDetails);
				updateChatter.setDate(new Date());
				updateChatter.setFollowedId(leadId);
				updateChatter.setFollowType(FOLLOWTYPE.People.getType());
				updateChatter.setUpdateType(UPDATETYPE.Edited.getName());
				
//				Post post = new Post();
//				post.setPostDate(new Date());
//				post.setPoster(userDetails);
//				String postText = "<a href='/sales/s/viewLead.html?id="+leadId+"'>i converted Lead Name:"+ lead.getfName() + " "+lead.getlName()+"</a>";
//				post.setPostText(postText);
//				postService.addPost(post);	
//				updateChatter.setPost(post);
//				updateChatterService.add(updateChatter);
				/////////////////////////////////
				joinRequestService.getJoinRquestNo(session, model);
				calendarService.getAppointmentEventsNo(session, model);
				calendarService.getCallEventssNo(session, model);
		return "redirect:/s/leads.html";
	}
	
	@RequestMapping(value="/newLead" ,method=RequestMethod.GET)
	public String getNewLead(Model model ,HttpSession session,HttpServletRequest request,HttpServletResponse response, ModelMap modelMap){
		if (SecurityUtils.getSubject().hasRole("leadAdd")){
		try {
			request.setCharacterEncoding("UTF-8");
//			response.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/s/login.html";
		}
		List<String> cars = new ArrayList<String>();
		cars.add("--none--");
		cars.add("5");
		cars.add("10");
		cars.add("20");
		cars.add("50");
		cars.add("100");
		cars.add("250");
		cars.add("500");
		cars.add("1000");
		cars.add("1500");
		model.addAttribute("cars", cars);
		
		Employee userDetails = (Employee)session.getAttribute("userDetails");
		LeadForm leadForm = new LeadForm();
		leadForm.setOwnerName(userDetails.getfName());
		leadForm.setOwnerId(userDetails.getId());
		modelMap.addAttribute("leadForm", leadForm);
//		List<Rating> ratings = ratingService.getAllRating();
		RATING[] ratings = RATING.values();
		model.addAttribute("ratings", ratings);
//		List<LeadSource> leadSources = leadSourceService.getAllLeadSource();
		LEADSOURCE[] leadSources = LEADSOURCE.values();
//		List<LeadStatus> leadStatus = leadStatusService.getAllLeadStatus();
		LEADSTATUS[] leadStatus = LEADSTATUS.values();
//		List<INDUSTRY> industries = industeryService.getAllIndustery();
		INDUSTRY[] industries = INDUSTRY.values();
		model.addAttribute("leadSources", leadSources);
		model.addAttribute("leadStatus", leadStatus);
		model.addAttribute("industries", industries);
		model.addAttribute("userDetails",userDetails);
		List<Country> countries = new ArrayList<Country>();
		countries =  countryService.getAll();
		model.addAttribute("countries",countries);
		//List<City> cities = new ArrayList<City>();
		//cities = cityService.getAllCities();
		//model.addAttribute("cities",cities);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "newLead";
		
		}
		else{
			joinRequestService.getJoinRquestNo(session, model);
			calendarService.getAppointmentEventsNo(session, model);
			calendarService.getCallEventssNo(session, model);
			return "accessDenied";
		}
	}
	
	@RequestMapping(value="/newLead" ,method=RequestMethod.POST)
	public String postNewLead(HttpSession session,HttpServletRequest request,HttpServletResponse response,
			Model model, ModelMap modelMap,
			@Valid @ModelAttribute("leadForm") LeadForm leadForm,BindingResult result){
		try {
			request.setCharacterEncoding("UTF-8");
//			response.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/s/login.html";
		}
		System.out.println(">>>>>>>>>>>>>inside post of new Lead++++++++++++++++++++++++++");
	    
		 
		Lead lead = new Lead();
		Contact contact =new Contact();
		Employee leadOwner = (Employee)session.getAttribute("userDetails");
		
		List<String> cars = new ArrayList<String>();
		cars.add("--none--");
		cars.add("5");
		cars.add("10");
		cars.add("20");
		cars.add("50");
		cars.add("100");
		cars.add("250");
		cars.add("500");
		cars.add("1000");
		cars.add("1500");
		model.addAttribute("cars",cars);
		List<Lead> leads = leadService.getLeads(leadOwner.getId());
		if(leads.size()>0){
			for (Lead lead2 : leads) {
				if(leadForm.getPhone()!=null&&!leadForm.getPhone().equalsIgnoreCase("")){
					if(lead2.getPhone()!=null&&!lead2.getPhone().equalsIgnoreCase("")){
						if(lead2.getPhone().equalsIgnoreCase(leadForm.getPhone())){
							result.rejectValue("phone", "phone","this phone already exists");
						}
					}
				}
				if(leadForm.getCompanyName()!=null&&!leadForm.getCompanyName().equalsIgnoreCase("")){
					if(lead2.getCompanyName()!=null&&!lead2.getCompanyName().equalsIgnoreCase("")){
						if(lead2.getCompanyName().equalsIgnoreCase(leadForm.getCompanyName())){
							result.rejectValue("companyName", "companyName","this company already exists");
						}
					}
				}
				if(leadForm.getMobile()!=null&&!leadForm.getMobile().equalsIgnoreCase("")){
					if(lead2.getMobile()!=null&&!lead2.getMobile().equalsIgnoreCase("")){
						if(lead2.getMobile().equalsIgnoreCase(leadForm.getMobile())){
							result.rejectValue("mobile", "mobile","this mobile already exists");
						}
					}
				}
			}
		}
		
		if(result.hasErrors()){
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>....."+result.getAllErrors().size());
			model.addAttribute("cars",cars);
			RATING[] ratings = RATING.values();
			model.addAttribute("ratings", ratings);
			LEADSOURCE[] leadSources = LEADSOURCE.values();
			LEADSTATUS[] leadStatus = LEADSTATUS.values();
		
			INDUSTRY[] industries = INDUSTRY.values();
			model.addAttribute("leadSources", leadSources);
			model.addAttribute("leadStatus", leadStatus);
			model.addAttribute("industries", industries);
			model.addAttribute("userDetails",leadOwner);
			List<Country> countries = new ArrayList<Country>();
			countries =  countryService.getAll();
			List<City> cities = new ArrayList<City>();
			cities = cityService.getAllCityByCountryId(leadForm.getCountry());
			model.addAttribute("cities",cities);
			model.addAttribute("countries",countries);
			joinRequestService.getJoinRquestNo(session, model);
			calendarService.getAppointmentEventsNo(session, model);
			calendarService.getCallEventssNo(session, model);
			model.addAttribute("leadForm", leadForm);
			return "newLead";
		}
				
		lead.setLeadOwner(leadOwner);
		contact.setCreator(leadOwner);
		contact.setViewType("lead");
		try {
			if(leadForm.getAnnualRevenue() != null){
				lead.setAnnualRevenue(leadForm.getAnnualRevenue());
				
			}
		} catch (Exception e) {
			// TODO: handle exception
			lead.setAnnualRevenue(0);
			System.out.println("################# not a number ################");
		}
		if(leadForm.getCompanyName() != null && !leadForm.getCompanyName().equalsIgnoreCase("")){
			lead.setCompanyName(leadForm.getCompanyName());
		}
		Integer cityId=leadForm.getCity();
		if(leadForm.getCity()!=null && !cityId.equals(0)){
				lead.setCity(cityService.getCityById(leadForm.getCity()));
		}
		if(leadForm.getCountry() != null){
			lead.setCountry(countryService.getCountryById(leadForm.getCountry()));
		}
		if(leadForm.getDescription() != null && !leadForm.getDescription().equalsIgnoreCase("")){
			lead.setDescription(leadForm.getDescription());
		}
		if(leadForm.getEmail() != null && !leadForm.getEmail().equalsIgnoreCase("")){
			lead.setEmail(leadForm.getEmail());
			contact.setEmail(leadForm.getEmail());
		}
		if(leadForm.getEmpNum() != null){
			lead.setNumOfEmp(leadForm.getEmpNum());
		}
		if(leadForm.getfName() != null && !leadForm.getfName().equalsIgnoreCase("")){
			lead.setfName(leadForm.getfName());
			contact.setfName(leadForm.getfName());
		}
		if(leadForm.getIndustry() != null){
			INDUSTRY[] industries = INDUSTRY.values();
			lead.setIndustry(leadForm.getIndustry());
		}
		if(leadForm.getLeadId() != null){
			lead.setId(leadForm.getLeadId());
		}
		if(leadForm.getLeadSource()!= null&&!(leadForm.getLeadSource().equalsIgnoreCase(""))){
			lead.setLeadSource(leadForm.getLeadSource());
		}
//		if(leadForm.getLeadSource() != null){
//			LEADSOURCE[] leadsource = LEADSOURCE.values();
//			lead.setLeadSource(leadsource[leadForm.getLeadSource()].getName());
//			contact.setLeadSource(leadsource[leadForm.getLeadSource()].getName());
//		}
		if(leadForm.getLeadStatus() != null){
            LEADSTATUS[] leadstatus = LEADSTATUS.values();
            lead.setLeadStatus(leadstatus[leadForm.getLeadStatus()].getName());
    }

		if(leadForm.getlName() != null && !leadForm.getlName().equalsIgnoreCase("")){
			lead.setlName(leadForm.getlName());
			contact.setlName(leadForm.getlName());
		}
		if(leadForm.getPhone() != null && !leadForm.getPhone().equalsIgnoreCase("")){
			lead.setPhone(leadForm.getPhone());
			contact.setPhone(leadForm.getPhone());
		}
		if(leadForm.getMobile() != null && !leadForm.getMobile().equalsIgnoreCase("")){
			lead.setMobile(leadForm.getMobile());
			contact.setMobile(leadForm.getMobile());
		}
		if(leadForm.getRating() != null){
			RATING[] ratings = RATING.values();
			lead.setRating( ratings[leadForm.getRating()].getName());
		}
		if(leadForm.getState() != null && !leadForm.getState().equalsIgnoreCase("")){
			lead.setState(leadForm.getState());
		}
		if(leadForm.getStreet() != null && !leadForm.getStreet().equalsIgnoreCase("")){
			lead.setStreet(leadForm.getStreet());
		}
		if(leadForm.getTitle() != null && !leadForm.getTitle().equalsIgnoreCase("")){
			lead.setTitle(leadForm.getTitle());
			contact.setTitle(leadForm.getTitle());
		}
		if(leadForm.getWebsite() != null && !leadForm.getWebsite().equalsIgnoreCase("")){
			lead.setWebSite(leadForm.getWebsite());
		}
		if(leadForm.getZipCode() != null && !leadForm.getZipCode().equalsIgnoreCase("")){
			lead.setZipCode(leadForm.getZipCode());
		}
		if(leadForm.getInOutBound() != null && !leadForm.getInOutBound().equalsIgnoreCase("")){
			lead.setInOutBound(leadForm.getInOutBound().toString());
		}
		if(leadForm.getCarsNum() != null){
			lead.setCarsNum(leadForm.getCarsNum());
		}
		if(leadForm.getCategory() != null && !leadForm.getCategory().equalsIgnoreCase("")){
			lead.setCategory(leadForm.getCategory());
		}
		lead.setIsConverted(false);
		lead.setIsDeleted(false);
		contact.setIsDeleted(false);
//		lead.setCategory(category);
//		lead.setCarsNum(carsNum);
//		lead.setInOutBound(inOutBound);
		Date date = new Date();
		lead.setDateCreated(date);
		contact.setDateCreated(date);
		leadService.addLead(lead);
		contact.setParentName("lead");
		contact.setParentId(lead.getId());
		contact.setDateCreated(date);
		contact.setDateModified(date);
		contactService.addContact(contact);
		
		//save post to view on chatter page
//		FollowType followType = followTypeService.getFollowTypeById(5);
////				UpdateType updateType = updateTypeService.getById(3);
//				UpdateChatter updateChatter = new UpdateChatter();
//				updateChatter.setAction_emp(leadOwner);
//				updateChatter.setDate(new Date());
//				updateChatter.setFollowedId(lead.getId());
//				updateChatter.setFollowType(FOLLOWTYPE.People.getType());
//				updateChatter.setUpdateType(UPDATETYPE.Followed.getName());
//				
//				Post post = new Post();
//				post.setPostDate(new Date());
//				post.setPoster(leadOwner);
//				String postText = "<a href='/sales/s/viewLead.html?id="+lead.getId()+"'>i created Lead Name:"+lead.getfName() +" "+lead.getlName()+"</a>";
//				post.setPostText(postText);
//				postService.addPost(post);	
//				updateChatter.setPost(post);
//				updateChatterService.add(updateChatter);
				joinRequestService.getJoinRquestNo(session, model);
				calendarService.getAppointmentEventsNo(session, model);
				calendarService.getCallEventssNo(session, model);
		return  "redirect:/s/leads.html";
	}
		
	@RequestMapping(value="/editLead" ,method=RequestMethod.GET)
	public String getEditLead(HttpSession session,Model model,HttpServletRequest request,HttpServletResponse response){
		if (SecurityUtils.getSubject().hasRole("leadEdit")){			
		try {
			request.setCharacterEncoding("UTF-8");
//			response.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/s/login.html";
		}

		Employee userDetails = (Employee)session.getAttribute("userDetails");
		model.addAttribute("userDetails",userDetails);
		RATING[] ratings = RATING.values();
//		List<Rating> ratings = ratingService.getAllRating();
	    model.addAttribute("ratings", ratings);
//		List<LeadSource> leadSources = leadSourceService.getAllLeadSource();
		LEADSOURCE[] leadSources = LEADSOURCE.values();
//		List<LeadStatus> leadStatus = leadStatusService.getAllLeadStatus();
		LEADSTATUS[] leadStatus = LEADSTATUS.values();
	
//		List<INDUSTRY> industries = industeryService.getAllIndustery();
		INDUSTRY[] industries = INDUSTRY.values();
		List<Country>countries = countryService.getAll();
		model.addAttribute("leadSources", leadSources);
		model.addAttribute("leadStatus", leadStatus);
		model.addAttribute("industries", industries);
		 Lead lead = leadService.getLeadById(Integer.parseInt(request.getParameter("id").toString()));
		 LeadConverter leadConverter = new LeadConverter();
		 LeadForm leadForm = leadConverter.leadToLeadFormConverter(lead);
//		 System.out.println(leadForm.getTitle());
//		 System.out.println(leadForm.getEmail());
//		 System.out.println(leadForm.getPhone());
//		 System.out.println(leadForm.getStreet());
//		 System.out.println( leadForm.getZipCode());
//		 System.out.println(leadForm.getCountry());
//		 System.out.println(leadForm.getCity());
//		 System.out.println(leadForm.getState());
//		 System.out.println(leadForm.getWebsite());
//		 System.out.println(leadForm.getEmpNum());
//		 System.out.println(leadForm.getAnnualRevenue());
//		 System.out.println(leadForm.getDescription());
		 List<City> cities = new ArrayList<City>();
		 if(leadForm.getCountry() != null ){
			 cities = cityService.getAllCityByCountryId(leadForm.getCountry());
		 }
		 if(lead.getIndustry()!= null){
			 leadForm.setIndustry(lead.getIndustry());
		 }else{
			 leadForm.setIndustry(new String());
		 }
		 
		 List<String> cars = new ArrayList<String>();
			cars.add("--none--");
			cars.add("5");
			cars.add("10");
			cars.add("20");
			cars.add("50");
			cars.add("100");
			cars.add("250");
			cars.add("500");
			cars.add("1000");
			cars.add("1500");
			model.addAttribute("cars",cars);
			
		 model.addAttribute("leadForm", leadForm);
		 model.addAttribute("countries", countries);
		 model.addAttribute("cities", cities);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "editLead";
		}
		else{
			return "accessDenied";
		}
	}
	
	@RequestMapping(value="/editLead" ,method=RequestMethod.POST)
	public String postEditLead(HttpSession session,HttpServletRequest request,HttpServletResponse response,Model model,
		/*	@RequestParam(value="fname",required =false) String fname,
			@RequestParam(value="company",required =false) String company,
			@RequestParam(value="status",required =false) Integer status,
			@RequestParam(value="lname",required =false) String lname,
			@RequestParam(value="title",required =false) String title,
			@RequestParam(value="phone",required =false) String phone,
			@RequestParam(value="email",required =false) String email,
			@RequestParam(value="rating",required =false) Integer rating,
			@RequestParam(value="city",required =false) Integer city,
			@RequestParam(value="state",required =false) String state,
			@RequestParam(value="zipcode",required =false) String zipcode,
			@RequestParam(value="website",required =false) String website,
			@RequestParam(value="empnum",required =false) Integer empnum,
			@RequestParam(value="annual",required =false) Integer annual,
			@RequestParam(value="description",required =false) String description,
			@RequestParam(value="leadsource",required =false) Integer leadsource,
			@RequestParam(value="industry",required =false) Integer industry,
			@RequestParam(value="id",required =false) Integer id,
			@RequestParam(value="street",required =false) String street,
			@RequestParam(value="country",required =false) Integer countryId*/
			@Valid @ModelAttribute("leadForm") LeadForm leadForm,BindingResult result){
		try {
			request.setCharacterEncoding("UTF-8");
//			response.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Employee leadOwner = (Employee)session.getAttribute("userDetails");
		
		
			System.out.println(">>>>>>>>>>>><<<<<<<<<<<<<<<<>>>>>>>>>>><<<<<<<<"+request.getCharacterEncoding());
			
			// TODO Auto-generated catch block
	//	Integer integer = Integer.parseInt(request.getParameter("id").toString());
	//	System.out.println("============================================================================="+id);
		Lead lead =leadService.loadLead(leadForm.getLeadId());
		lead.setLeadOwner(leadOwner);
		//System.out.println(">>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"+lead.getfName());
		
		List<String> cars = new ArrayList<String>();
		cars.add("--none--");
		cars.add("5");
		cars.add("10");
		cars.add("20");
		cars.add("50");
		cars.add("100");
		cars.add("250");
		cars.add("500");
		cars.add("1000");
		cars.add("1500");
		model.addAttribute("cars",cars);
		List<Lead> leads = leadService.getLeads(leadOwner.getId());
		if(leads.size()>0){
			for (Lead lead2 : leads) {
				if(leadForm.getPhone()!=null&&!leadForm.getPhone().equalsIgnoreCase("")){
					if(lead2.getPhone()!=null&&!lead2.getPhone().equalsIgnoreCase("")){
						if(lead2.getPhone().equalsIgnoreCase(leadForm.getPhone())){
							result.rejectValue("phone", "phone","this phone already exists");
						}
					}
				}
				if(leadForm.getCompanyName()!=null&&!leadForm.getCompanyName().equalsIgnoreCase("")){
					if(lead2.getCompanyName()!=null&&!lead2.getCompanyName().equalsIgnoreCase("")){
						if(lead2.getCompanyName().equalsIgnoreCase(leadForm.getCompanyName())){
							result.rejectValue("companyName", "companyName","this company already exists");
						}
					}
				}
				if(leadForm.getMobile()!=null&&!leadForm.getMobile().equalsIgnoreCase("")){
					if(lead2.getMobile()!=null&&!lead2.getMobile().equalsIgnoreCase("")){
						if(lead2.getMobile().equalsIgnoreCase(leadForm.getMobile())){
							result.rejectValue("mobile", "mobile","this mobile already exists");
						}
					}
				}
			}
		}
		if(result.hasErrors()){
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>....."+result.getAllErrors().size());
			//model.addAttribute("cars",cars);
//			List<Rating> ratings = ratingService.getAllRating();
			RATING[] ratings = RATING.values();
			model.addAttribute("ratings", ratings);
//			List<LeadSource> leadSources = leadSourceService.getAllLeadSource();
			LEADSOURCE[] leadSources = LEADSOURCE.values();
//			List<LeadStatus> leadStatus = leadStatusService.getAllLeadStatus();
			LEADSTATUS[] leadStatus = LEADSTATUS.values();
		
//			List<INDUSTRY> industries = industeryService.getAllIndustery();
			INDUSTRY[] industries = INDUSTRY.values();
			model.addAttribute("leadSources", leadSources);
			model.addAttribute("leadStatus", leadStatus);
			model.addAttribute("industries", industries);
			List<Country> countries = new ArrayList<Country>();
			List<City> cities = new ArrayList<City>();
			if(leadForm.getCountry() != null ){
				 cities = cityService.getAllCityByCountryId(leadForm.getCountry());
			 }
			model.addAttribute("cities",cities);
			countries =  countryService.getAll();
			model.addAttribute("countries",countries);
			
			joinRequestService.getJoinRquestNo(session, model);
			calendarService.getAppointmentEventsNo(session, model);
			calendarService.getCallEventssNo(session, model);
			model.addAttribute("leadForm", leadForm);
			return "editLead";
		}
		if(leadForm.getRating() != null){
//			Rating rating2 =  ratingService.getRatingById(rating);
			RATING[] rating2 = RATING.values();
			lead.setRating(rating2[leadForm.getRating()].getName());
		}
		if(leadForm.getIndustry() != null){
//			INDUSTRY industry2 = industeryService.getIndusteryById(industry);
			INDUSTRY[] industry2 = INDUSTRY.values();
			lead.setIndustry(leadForm.getIndustry());
		}
		if(leadForm.getLeadStatus() != null){
            LEADSTATUS[] leadstatus = LEADSTATUS.values();
            lead.setLeadStatus(leadstatus[leadForm.getLeadStatus()].getName());
    }

		if(leadForm.getLeadSource()!= null&&!(leadForm.getLeadSource().equalsIgnoreCase(""))){
			lead.setLeadSource(leadForm.getLeadSource());
		}
//		if(leadForm.getLeadSource() != null){
////			LeadSource leadSource2 = leadSourceService.getLeadSourceById(leadsource);
//			LEADSOURCE[] leadSource2 = LEADSOURCE.values();
//			lead.setLeadSource(leadSource2[leadForm.getLeadSource()].getName());
//		}
		if(leadForm.getCountry() != null && !leadForm.getCountry().equals("")){
			Country country2 = countryService.getCountryById(leadForm.getCountry());
			lead.setCountry(country2);
		}
		
		Integer cityId=leadForm.getCity();
		if(leadForm.getCity()!=null && !cityId.equals(0)){
			City city2 = cityService.getCityById(leadForm.getCity());
			lead.setCity(city2);
		}
		else{
			lead.setCity(null);
		}
		if(leadForm.getlName() != null && !leadForm.getlName().equalsIgnoreCase("")){
			lead.setlName(leadForm.getlName());
		}
		if(leadForm.getfName() != null && !leadForm.getfName().equalsIgnoreCase("")){
			lead.setfName(leadForm.getfName());
		}
		if(leadForm.getCompanyName() != null && !leadForm.getCompanyName().equalsIgnoreCase("")){
			lead.setCompanyName(leadForm.getCompanyName());
		}
		if(leadForm.getAnnualRevenue() != null){
			lead.setAnnualRevenue(leadForm.getAnnualRevenue());
		}
		if(leadForm.getEmpNum() != null){
			lead.setNumOfEmp(leadForm.getEmpNum());
		}
		if(leadForm.getDescription() != null && !leadForm.getDescription().equalsIgnoreCase("")){
			lead.setDescription(leadForm.getDescription());
		}
		if(leadForm.getWebsite() != null && !leadForm.getWebsite().equalsIgnoreCase("")){
			lead.setWebSite(leadForm.getWebsite());
		}
		if(leadForm.getPhone() != null && !leadForm.getPhone().equalsIgnoreCase("")){
			lead.setPhone(leadForm.getPhone());
		}
		if(leadForm.getMobile() != null && !leadForm.getMobile().equalsIgnoreCase("")){
			lead.setMobile(leadForm.getMobile());
			//contact.setPhone(leadForm.getPhone());
		}
		if(leadForm.getTitle() != null && !leadForm.getTitle().equalsIgnoreCase("")){
			lead.setTitle(leadForm.getTitle());
		}
		if(leadForm.getEmail() != null && !leadForm.getEmail().equalsIgnoreCase("")){
			lead.setEmail(leadForm.getEmail());
		}
		if(leadForm.getZipCode() != null && !leadForm.getZipCode().equalsIgnoreCase("")){
			lead.setZipCode(leadForm.getZipCode());
		}
		if(leadForm.getState() != null && !leadForm.getState().equalsIgnoreCase("")){
			lead.setState(leadForm.getState());
		}
		if(leadForm.getStreet() != null && !leadForm.getStreet().equalsIgnoreCase("")){
			lead.setStreet(leadForm.getStreet());
		}
		if(leadForm.getInOutBound() != null && !leadForm.getInOutBound().equalsIgnoreCase("")){
			lead.setInOutBound(leadForm.getInOutBound().toString());
		}
		if(leadForm.getCarsNum() != null){
			lead.setCarsNum(leadForm.getCarsNum());
		}
		if(leadForm.getCategory() != null && !leadForm.getCategory().equalsIgnoreCase("")){
			lead.setCategory(leadForm.getCategory());
		}
//		char []chars =fname.toCharArray();
//		Character c = (char)chars[0];
		//lead.setfName(fname);
		//lead.setCompanyName(company);
		//lead.setlName(lname);
		
		//lead.setAnnualRevenue(annual);
		//lead.setNumOfEmp(empnum);
		//lead.setDescription(description);
		//lead.setWebSite(website);
		//lead.setPhone(phone);
		//lead.setTitle(title);
		//lead.setEmail(email);
		//lead.setZipCode(zipcode);
		//lead.setState(state);
		//lead.setStreet(street);
		System.out.println(">>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"+lead.getfName());
		lead.setIsDeleted(false);
		lead.setIsConverted(false);
		lead.setDateModified(new Date());
		leadService.saveOrupdate(lead);
		
		//save post to view on chatter page
//		FollowType followType = followTypeService.getFollowTypeById(3);
//				UpdateType updateType = updateTypeService.getById(1);
//				UpdateChatter updateChatter = new UpdateChatter();
//				updateChatter.setAction_emp(leadOwner);
//				updateChatter.setDate(new Date());
//				updateChatter.setFollowedId(lead.getId());
//				updateChatter.setFollowType(FOLLOWTYPE.Lead.getType());
//				updateChatter.setUpdateType(UPDATETYPE.Edited.getName());
//				
//				Post post = new Post();
//				post.setPostDate(new Date());
//				post.setPoster(leadOwner);
//				String postText = "<a href='/sales/s/viewLead.html?id="+lead.getId()+"'>i edited Lead Name:"+lead.getfName() +" "+lead.getlName()+"</a>";
//				post.setPostText(postText);
//				postService.addPost(post);	
//				updateChatter.setPost(post);
//				updateChatterService.add(updateChatter);
				model.addAttribute("leadOwner",leadOwner);
				joinRequestService.getJoinRquestNo(session, model);
				calendarService.getAppointmentEventsNo(session, model);
				calendarService.getCallEventssNo(session, model);
		return "redirect:/s/leads.html";
	}
	
	@RequestMapping(value="/deleteLead" ,method=RequestMethod.GET)
	public String getdeleteLead(HttpSession session,Model model,HttpServletRequest request,HttpServletResponse response){
		if (SecurityUtils.getSubject().hasRole("leadDelete")){
		try {
			request.setCharacterEncoding("UTF-8");
//			response.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Employee userDetails=(Employee)session.getAttribute("userDetails");
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/s/login.html";
		}
		
		 Lead lead = leadService.loadLead(Integer.parseInt(request.getParameter("id").toString()));
		//save post to view on chatter page
//		FollowType followType = followTypeService.getFollowTypeById(3);
//				UpdateType updateType = updateTypeService.getById(2);
//				UpdateChatter updateChatter = new UpdateChatter();
//				updateChatter.setAction_emp(userDetails);
//				updateChatter.setDate(new Date());
//				updateChatter.setFollowedId(lead.getId());
//				updateChatter.setFollowType(FOLLOWTYPE.Lead.getType());
//				updateChatter.setUpdateType(UPDATETYPE.Deleted.getName());
//				
//				Post post = new Post();
//				post.setPostDate(new Date());
//				post.setPoster(userDetails);
//				String postText = "<a href='/sales/s/viewLead.html?id="+lead.getId()+"'>i deleted Lead Name:"+lead.getfName() +" "+lead.getlName()+"</a>";
//				post.setPostText(postText);
//				postService.addPost(post);	
//				updateChatter.setPost(post);
//				updateChatterService.add(updateChatter);
				
		
		 //leadService.deleteLead(lead);
				DeletedLead deletedLead = new DeletedLead();
				deletedLead.setDeleatedId(lead.getId());
				deletedLead.setDeleterId(userDetails.getId());
				deletedLeadService.addDeletedLead(deletedLead);
				lead.setIsDeleted(true);
				Date date =new Date();
				lead.setDateModified(date);
				leadService.saveOrupdate(lead);
			    model.addAttribute("userDetails",userDetails);
			    joinRequestService.getJoinRquestNo(session, model);
			    calendarService.getAppointmentEventsNo(session, model);
			    calendarService.getCallEventssNo(session, model);
			return "redirect:/s/leads.html";
		}
		else{
			return "accessDenied";
		}
	}
	@RequestMapping(value="/deleteSelectedLead" ,method=RequestMethod.POST)
	@ResponseBody
	public GenericCrud getSelectedLead(HttpSession session,Model model,HttpServletRequest request,@RequestParam Integer id){
		GenericCrud genericcrud = new GenericCrud();
		System.out.println("DELETE SELECTED LEAD>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.."+id);
		if (SecurityUtils.getSubject().hasRole("leadDelete")){
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Employee userDetails=(Employee)session.getAttribute("userDetails");
		
		 Lead lead = leadService.loadLead(id);
				UpdateChatter updateChatter = new UpdateChatter();
				updateChatter.setAction_emp(userDetails);
				updateChatter.setDate(new Date());
				updateChatter.setFollowedId(lead.getId());
				updateChatter.setFollowType(FOLLOWTYPE.Lead.getType());
				updateChatter.setUpdateType(UPDATETYPE.Deleted.getName());
				
//				Post post = new Post();
//				post.setPostDate(new Date());
//				post.setPoster(userDetails);
//				String postText = "<a href='/sales/s/viewLead.html?id="+lead.getId()+"'>i deleted Lead Name:"+lead.getfName() +" "+lead.getlName()+"</a>";
//				post.setPostText(postText);
//				postService.addPost(post);	
//				updateChatter.setPost(post);
//				updateChatterService.add(updateChatter);
				DeletedLead deletedLead = new DeletedLead();
				deletedLead.setDeleatedId(lead.getId());
				deletedLead.setDeleterId(userDetails.getId());
				deletedLeadService.addDeletedLead(deletedLead);
				lead.setIsDeleted(true);
				Date date =new Date();
				lead.setDateModified(date);
				leadService.saveOrupdate(lead);
			    model.addAttribute("userDetails",userDetails);
			    joinRequestService.getJoinRquestNo(session, model);
			    calendarService.getAppointmentEventsNo(session, model);
			    calendarService.getCallEventssNo(session, model);
				genericcrud.setResult("OK");
			return genericcrud;
		}
		else{
			System.out.println("ERROR>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
			genericcrud.setResult("ERROR");
			return genericcrud;
		}
	}
	@RequestMapping(value="/viewLead",method=RequestMethod.GET)
	public String viewLead(Model model,HttpSession session,HttpServletRequest request,HttpServletResponse response) {
		if (SecurityUtils.getSubject().hasRole("leadView")){
		try {
			request.setCharacterEncoding("UTF-8");
//			response.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Employee userDetails=(Employee)session.getAttribute("userDetails");
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/s/login.html";
		}
			Lead lead = leadService.getLeadById(Integer.parseInt(request.getParameter("id")));
		ActionType actionType = new ActionType();
		List<ActionType> actionTypes = actionTypeService.getActionTypes(actionType);
		System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@" + actionTypes.size());
		response.setCharacterEncoding("UTF-8");
		List<Call> calls =callService.getCallByParentId(Integer.parseInt(request.getParameter("id")), "lead");
		model.addAttribute("calls", calls);
		List<Appointment> appointments =appointmentService.getAppointmentByParentId(Integer.parseInt(request.getParameter("id")), "lead");
		model.addAttribute("appointments", appointments);
		System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@************************@@@@@@@@@@@@@@@@@@@@@@@@" + appointments.size());
		model.addAttribute("lead", lead);
		model.addAttribute("actionTypes", actionTypes);
		model.addAttribute("userDetails", userDetails);
		List<User> users = userShiroService.getAllUsers(userDetails);
		//List<Role> roles = roleShiroService.getAllRoles();
		User user = users.get(0);
		List<Role>userRoles=user.getRoles();
		
		List<String>roles = new ArrayList<String>();
		for (Role role : userRoles) {
			roles.add(role.getName());
		}
		model.addAttribute("userRoles", roles);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		joinRequestService.getJoinRquestNo(session, model);
		return "viewLead";
		}
		else{
			return "accessDenied";
		}
	}
	@RequestMapping(value="/new-action-eg",method=RequestMethod.POST)
	public String newActionPost(Model model,HttpSession session,HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value="actionType",required =false) Integer typeId,
			@RequestParam(value="parentId",required =false) Integer parentId) {
		try {
			request.setCharacterEncoding("UTF-8");
//			response.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Employee userDetails=(Employee)session.getAttribute("userDetails");
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/s/login.html";
		}
		//List<ActionField> actionFields = actionFieldService.getFieldsByTypeId(typeId);
		//System.out.println("ffffffffffffffffffffffffffffffffffff" +typeId);
		//System.out.println("ffffffffffffffffffffffffffffffffffff" + actionFields.size());
		//model.addAttribute("actionFields", actionFields);
		model.addAttribute("parentId", parentId);
		model.addAttribute("userDetails", userDetails);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "redirect:/s/new-action.html?typeId=" + typeId + "&parentId=" + parentId;
	}
	@RequestMapping(value="/importLeads",method=RequestMethod.GET)
	public String importLeads(Model model,HttpSession session,HttpServletRequest request) {
		if (SecurityUtils.getSubject().hasRole("leadImport")){
		Employee userDetails=(Employee)session.getAttribute("userDetails");
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/login.html";
		}
		//model.addAttribute("flagError", false);
		model.addAttribute("userDetails", userDetails);
		model.addAttribute("leadForm", new LeadForm());
		LeadColumnsForm columnsForm = new LeadColumnsForm();
		model.addAttribute("columnsForm", columnsForm);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "importLeads";
		}
		else{
			return "accessDenied";
		}
	}
	@RequestMapping(value="/importLeads",method=RequestMethod.POST)
    public String importLeads(Model model,HttpSession session,HttpServletRequest request,HttpServletResponse response,
                    @RequestParam(value="fileInput",required=false) MultipartFile fileInput,
                    @RequestParam(value="flag",required=false)String flag,
                    @Valid @ModelAttribute("columnsForm") LeadColumnsForm columnsForm,BindingResult result) {
            Employee userDetails=(Employee)session.getAttribute("userDetails");
            if(null ==session.getAttribute("userDetails") ){
                    return "redirect:/login.html";
            }
            model.addAttribute("userDetails", userDetails);
            try {                   
                    Map<String, String> cellMapping = new HashMap<String, String>();
	                 cellMapping.put("A", "leadId");
	                 cellMapping.put("B", "callDate");
	                 cellMapping.put("C", "leadInterseted");
	                 cellMapping.put("D", "crm");
	                 cellMapping.put("E", "leadStatus");
	                 cellMapping.put("F", "companyName");
	                 cellMapping.put("G", "sector");
	                 cellMapping.put("H", "contactedPerson");
	                 cellMapping.put("I", "jobTitle");
	                 cellMapping.put("J", "phones");
	                 cellMapping.put("K", "address");
	                 cellMapping.put("L", "email");
	                 cellMapping.put("M", "carsNum");
	                 cellMapping.put("N", "carsType");
	                 cellMapping.put("O", "contactedPersonNumber");
	                 cellMapping.put("P", "inOutBound");
	                 cellMapping.put("Q", "leadSource");
	                 cellMapping.put("R", "companyProfile");
	                 cellMapping.put("S", "comments");
	                 
	         		OPCPackage pkg = null;
	         		try {
	         			
	         			ExcelWorkSheetHandler<ExcelAssetLead> workSheetHandler = new ExcelWorkSheetHandler<ExcelAssetLead>(ExcelAssetLead.class, cellMapping);
	         			
	         			pkg = OPCPackage.open(fileInput.getInputStream());
	         			ExcelReader excelReader = new ExcelReader(pkg, workSheetHandler);
	         			excelReader.process();

	         			if (workSheetHandler.getValueList().isEmpty()) {
	         				System.err.println("sHandler.getValueList() is empty; it means something went wrong parsing excel file");
	         			} else {
	         				List<ExcelAssetLead> leads = workSheetHandler.getValueList();
	         				for (ExcelAssetLead excelAssetLead : leads) {
								Lead lead = new Lead();
								Contact contact = new Contact();
								lead.setIsConverted(false);
								lead.setIsDeleted(false);
								lead.setIsFollowed(false);
								//lead.setLeadOwner(userDetails);
								if(excelAssetLead.getLeadId()!=null&&!excelAssetLead.getLeadId().equalsIgnoreCase("")){
									lead.setImportedleadId(excelAssetLead.getLeadId());
								}
								if(excelAssetLead.getCallDate()!=null&&!excelAssetLead.getCallDate().equalsIgnoreCase("")){
									lead.setDateCreated(new Date());
									contact.setDateCreated(new Date());
								}
								if(excelAssetLead.getLeadInterseted()!=null&&!excelAssetLead.getCallDate().equalsIgnoreCase("")){
									lead.setLeadStatus(excelAssetLead.getLeadInterseted());
									
								}
								if(excelAssetLead.getCrm()!=null&&!excelAssetLead.getCrm().equalsIgnoreCase("")){
									String email = excelAssetLead.getCrm().toString();
									System.out.println("email>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>."+email);
									Employee employee = employeeService.getEmployeeByEmail(email.toLowerCase());
									if(employee!=null){
										lead.setLeadOwner(employee);
										contact.setCreator(employee);
									}
								}
								
								if(excelAssetLead.getLeadStatus()!=null&&!excelAssetLead.getLeadStatus().equalsIgnoreCase("")){
									lead.setCategory(excelAssetLead.getLeadStatus());
								}
								if(excelAssetLead.getCompanyName()!=null&&!excelAssetLead.getCompanyName().equalsIgnoreCase("")){
									lead.setCompanyName(excelAssetLead.getCompanyName());
								}
								if(excelAssetLead.getSector()!=null&&!excelAssetLead.getSector().equalsIgnoreCase("")){
									lead.setIndustry(excelAssetLead.getSector());
								}
								if(excelAssetLead.getContactedPerson()!=null&&!excelAssetLead.getContactedPerson().equalsIgnoreCase("")){
									lead.setfName(excelAssetLead.getContactedPerson());
									contact.setfName(excelAssetLead.getContactedPerson());
								}
								if(excelAssetLead.getPhones()!=null&&!excelAssetLead.getPhones().equalsIgnoreCase("")){
									lead.setPhone(excelAssetLead.getPhones());
									lead.setPhone(excelAssetLead.getPhones());
								}
								if(excelAssetLead.getAddress()!=null&&!excelAssetLead.getAddress().equalsIgnoreCase("")){
									lead.setStreet(excelAssetLead.getAddress());
								}
								if(excelAssetLead.getEmail()!=null&&!excelAssetLead.getEmail().equalsIgnoreCase("")){
									lead.setEmail(excelAssetLead.getEmail());
									contact.setEmail(excelAssetLead.getEmail());
								}
//								if(excelAssetLead.getContactedPersonNumber()!=null&&!excelAssetLead.getContactedPersonNumber().equalsIgnoreCase("")){
//									lead.setNumOfEmp(excelAssetLead.getContactedPersonNumber());
//								}
								if(excelAssetLead.getComments()!=null&&!excelAssetLead.getComments().equalsIgnoreCase("")){
									lead.setDescription(excelAssetLead.getComments());
								}	
								leadService.addLead(lead);
								contact.setViewType(VIEWTYPE.Lead.getName());
								contact.setParentId(lead.getId());
                                contact.setParentName(lead.getfName());
                                contact.setIsDeleted(false);
                                contactService.addContact(contact);
							}
	         			}

	         		} catch (RuntimeException are) {
	         		} catch (InvalidFormatException ife) {
	         		} catch (IOException ioe) {
	         		} finally {
	         			try {
	         				if (null != pkg) {
	         					pkg.close();
	         				}
	         			} catch (IOException e) {
	         				// just ignore IO exception
	         			}
	         		}

            }catch(Exception exception){
                    exception.printStackTrace();
            }
            joinRequestService.getJoinRquestNo(session, model);
            calendarService.getAppointmentEventsNo(session, model);
            calendarService.getCallEventssNo(session, model);
            return  "redirect:/s/leads.html";
    }
   
//	@RequestMapping(value="/importCalls",method=RequestMethod.POST)
//    public String importCalls(Model model,HttpSession session,HttpServletRequest request,HttpServletResponse response,
//                    @RequestParam(value="fileInput",required=false) MultipartFile fileInput) {
//            Employee userDetails=(Employee)session.getAttribute("userDetails");
//            if(null ==session.getAttribute("userDetails") ){
//                    return "redirect:/login.html";
//            }
//            model.addAttribute("userDetails", userDetails);
//            try {                   
//                    Map<String, String> cellMapping = new HashMap<String, String>();
//	                 cellMapping.put("A", "callId");
//	                 cellMapping.put("B", "callDate");
//	                 cellMapping.put("C", "callDuration");
//	                 cellMapping.put("S", "comments");
//	                 cellMapping.put("S", "nextFollowUpDate");
//	                 
//	         		OPCPackage pkg = null;
//	         		try {
//	         			
//	         			ExcelWorkSheetHandler<ExcelCall> workSheetHandler = new ExcelWorkSheetHandler<ExcelCall>(ExcelCall.class, cellMapping);
//	         			
//	         			pkg = OPCPackage.open(fileInput.getInputStream());
//	         			ExcelReader excelReader = new ExcelReader(pkg, workSheetHandler);
//	         			excelReader.process();
//
//	         			if (workSheetHandler.getValueList().isEmpty()) {
//	         				System.err.println("sHandler.getValueList() is empty; it means something went wrong parsing excel file");
//	         			} else {
//	         				List<ExcelCall> calls = workSheetHandler.getValueList();
//	         				for (ExcelCall excelCall : calls) {
//	         					Lead lead = leadService.getLeadByImportedLeadId(excelCall.getCallId());
//	         					if(lead!=null){
//	         						if(lead.getHasCall()==null&&lead.getHasCall().equalsIgnoreCase("")){
//	         							Call call = new Call(){
//	         								
//	         							}
//	         						}
//	         					}
//								//Lead lead = new Lead();
//								lead.setIsConverted(false);
//								lead.setIsDeleted(false);
//								lead.setIsFollowed(false);
//								//lead.setLeadOwner(userDetails);
//								if(excelAssetLead.getLeadId()!=null&&!excelAssetLead.getLeadId().equalsIgnoreCase("")){
//									lead.setImportedleadId(excelAssetLead.getLeadId());
//								}
//								if(excelAssetLead.getCallDate()!=null&&!excelAssetLead.getCallDate().equalsIgnoreCase("")){
//									lead.setDate(new Date());
//								}
//								if(excelAssetLead.getLeadInterseted()!=null&&!excelAssetLead.getCallDate().equalsIgnoreCase("")){
//									lead.setLeadStatus(excelAssetLead.getLeadInterseted());
//								}
//								if(excelAssetLead.getCrm()!=null&&!excelAssetLead.getCrm().equalsIgnoreCase("")){
//									Employee employee = employeeService.getEmployeeByEmail(excelAssetLead.getEmail());
//									if(employee!=null){
//										lead.setLeadOwner(employee);
//									}
//								}
//								
//								if(excelAssetLead.getLeadStatus()!=null&&!excelAssetLead.getLeadStatus().equalsIgnoreCase("")){
//									lead.setCategory(excelAssetLead.getLeadStatus());
//								}
//								if(excelAssetLead.getCompanyName()!=null&&!excelAssetLead.getCompanyName().equalsIgnoreCase("")){
//									lead.setCompanyName(excelAssetLead.getCompanyName());
//								}
//								if(excelAssetLead.getSector()!=null&&!excelAssetLead.getSector().equalsIgnoreCase("")){
//									lead.setIndustry(excelAssetLead.getSector());
//								}
//								if(excelAssetLead.getContactedPerson()!=null&&!excelAssetLead.getContactedPerson().equalsIgnoreCase("")){
//									lead.setfName(excelAssetLead.getContactedPerson());
//								}
//								if(excelAssetLead.getPhones()!=null&&!excelAssetLead.getPhones().equalsIgnoreCase("")){
//									lead.setPhone(excelAssetLead.getPhones());
//								}
//								if(excelAssetLead.getAddress()!=null&&!excelAssetLead.getAddress().equalsIgnoreCase("")){
//									lead.setStreet(excelAssetLead.getAddress());
//								}
//								if(excelAssetLead.getEmail()!=null&&!excelAssetLead.getEmail().equalsIgnoreCase("")){
//									lead.setEmail(excelAssetLead.getEmail());
//								}
////								if(excelAssetLead.getContactedPersonNumber()!=null&&!excelAssetLead.getContactedPersonNumber().equalsIgnoreCase("")){
////									lead.setNumOfEmp(excelAssetLead.getContactedPersonNumber());
////								}
//								if(excelAssetLead.getComments()!=null&&!excelAssetLead.getComments().equalsIgnoreCase("")){
//									lead.setDescription(excelAssetLead.getComments());
//								}	
//								leadService.addLead(lead);
//							}
//	         			}
//
//	         		} catch (RuntimeException are) {
//	         		} catch (InvalidFormatException ife) {
//	         		} catch (IOException ioe) {
//	         		} finally {
//	         			try {
//	         				if (null != pkg) {
//	         					pkg.close();
//	         				}
//	         			} catch (IOException e) {
//	         				// just ignore IO exception
//	         			}
//	         		}
//
//            }catch(Exception exception){
//                    exception.printStackTrace();
//            }
//            joinRequestService.getJoinRquestNo(session, model);
//            calendarService.getAppointmentEventsNo(session, model);
//            calendarService.getCallEventssNo(session, model);
//            return  "redirect:/s/leads.html";
//    }
    private Map<String, String> getOnlyAssignedvalues(LeadColumnsForm leadColumnsForm){
            Map<String,String> map = new HashMap<String, String>();
            if(leadColumnsForm.getLeadOwner() != null && !leadColumnsForm.getLeadOwner().equalsIgnoreCase("") ){
                    map.put("leadOwner", leadColumnsForm.getLeadOwner());
            }
             if(leadColumnsForm.getAddress() != null && !leadColumnsForm.getAddress().equalsIgnoreCase("")){
                    map.put("address", leadColumnsForm.getAddress());
            }
             if(leadColumnsForm.getAnnualRevenue()!= null && !leadColumnsForm.getAnnualRevenue().equalsIgnoreCase("")){
                    map.put("annualRevenue", leadColumnsForm.getAnnualRevenue());
            }
            if(leadColumnsForm.getArea()!= null && !leadColumnsForm.getArea().equalsIgnoreCase("")){
                    map.put("area", leadColumnsForm.getArea());
            }
             if(leadColumnsForm.getCity()!= null && !leadColumnsForm.getCity().equalsIgnoreCase("")){
                    map.put("city", leadColumnsForm.getCity());
            }
             if(leadColumnsForm.getCompanyName()!= null && !leadColumnsForm.getCompanyName().equalsIgnoreCase("")){
                    map.put("companyName", leadColumnsForm.getCompanyName());
            }
             if(leadColumnsForm.getCountry()!= null && !leadColumnsForm.getCountry().equalsIgnoreCase("")){
                    map.put("country", leadColumnsForm.getCountry());
            }
             if(leadColumnsForm.getCreationDate()!= null && !leadColumnsForm.getCreationDate().equalsIgnoreCase("")){
                    map.put("creationDate", leadColumnsForm.getCreationDate());
            }
             if(leadColumnsForm.getDescription()!= null && !leadColumnsForm.getDescription().equalsIgnoreCase("")){
                    map.put("Description", leadColumnsForm.getDescription());
            }
             if(leadColumnsForm.getEmail()!= null && !leadColumnsForm.getEmail().equalsIgnoreCase("")){
                    map.put("email", leadColumnsForm.getEmail());
            }
             if(leadColumnsForm.getFirstName()!= null && !leadColumnsForm.getFirstName().equalsIgnoreCase("")){
                    map.put("firstName", leadColumnsForm.getFirstName());
            }
             if(leadColumnsForm.getIndustry()!= null && !leadColumnsForm.getIndustry().equalsIgnoreCase("")){
                    map.put("Industry", leadColumnsForm.getIndustry());
            }
             if(leadColumnsForm.getLastName()!= null && !leadColumnsForm.getLastName().equalsIgnoreCase("")){
                    map.put("lastName", leadColumnsForm.getLastName());
            }
             if(leadColumnsForm.getLeadSource()!= null && !leadColumnsForm.getLeadSource().equalsIgnoreCase("")){
                    map.put("leadSource", leadColumnsForm.getLeadSource());
            }
             if(leadColumnsForm.getLeadStatus()!= null && !leadColumnsForm.getLeadStatus().equalsIgnoreCase("")){
                    map.put("leadStatus", leadColumnsForm.getLeadStatus());
            }
             if(leadColumnsForm.getNumOfEmp()!= null && !leadColumnsForm.getNumOfEmp().equalsIgnoreCase("")){
                    map.put("numOfEmp", leadColumnsForm.getNumOfEmp());
            }
             if(leadColumnsForm.getPhone()!= null && !leadColumnsForm.getPhone().equalsIgnoreCase("")){
                    map.put("phone", leadColumnsForm.getPhone());
            }
             if(leadColumnsForm.getPostalCode()!= null && !leadColumnsForm.getPostalCode().equalsIgnoreCase("")){
                    map.put("postalCode", leadColumnsForm.getPostalCode());
            }
             if(leadColumnsForm.getRating()!= null && !leadColumnsForm.getRating().equalsIgnoreCase("")){
                    map.put("rating", leadColumnsForm.getRating());
            }
             if(leadColumnsForm.getTitle()!= null && !leadColumnsForm.getTitle().equalsIgnoreCase("")){
                    map.put("title", leadColumnsForm.getTitle());
            }
             if(leadColumnsForm.getWebSite()!= null && !leadColumnsForm.getWebSite().equalsIgnoreCase("")){
                    map.put("webSite", leadColumnsForm.getWebSite());
            }
            return map;
    }
   
    //////////////////getArabic chars/////////////////////////////////////
    private List<Character> findCharactersInUnicodeBlock(final Character.UnicodeBlock block,String string) {
        final List<Character> chars = new ArrayList<Character>();
        char[] incomingChars = string.toCharArray();
        List<Character> characters = new ArrayList<Character>();
        for (int i = 0; i < incomingChars.length; i++) {
                    for(int codePoint = Character.MIN_CODE_POINT; codePoint <= Character.MAX_CODE_POINT; codePoint++){
                             if (incomingChars[i] == (char) codePoint) {
                              //  in
                            }
                    }
            }
       
        return chars;
    }

    @RequestMapping(value="/deleteLeads",method=RequestMethod.GET)
	public String deleteLeads(Model model,HttpSession session,HttpServletRequest request,HttpServletResponse response) {
    	 Employee userDetails=(Employee)session.getAttribute("userDetails");
    	 List<Contact> contacts = contactService.getAllContactbyCompany(userDetails.getCompany().getCompanyName());
    	 for (Contact contact : contacts) {
    		 contactService.deleteContact(contact.getId());
		}
		 
    	 List<Lead>leads = leadService.getAllLead(userDetails.getCompany().getId());
    	 for (Lead lead : leads) {
			leadService.deleteLead(lead);
		}
    	 return "leads";
    }


}
